package com.chinasolf.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.chinasoft.model.user.UserInfo;
import com.chinasolf.result.R;
import com.chinasolf.utils.JwtHelper;
import com.chinasolf.yygh.user.service.UserInfoService;
import com.chinasolf.yygh.user.utils.ConstantPropertiesUtil;
import com.chinasolf.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
    @Autowired
    private UserInfoService userInfoService;
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {

        //第一步 获取临时票据 code
        //拿到code值请求微信固定接口地址，得到两个值,每次都得new对象
//        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
//                "?appid=" + ConstantPropertiesUtil.WX_OPEN_APP_ID
//                +"&secret=" + ConstantPropertiesUtil.WX_OPEN_APP_SECRET
//                +"&code=" +code
//                +"&&grant_type=authorization_code";
//
//        String result = HttpClientUtils.get(url);
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        //使用httpclient请求这个地址
        try {
            String resultInfo = HttpClientUtils.get(accessUrl);
            JSONObject jsonObject = JSONObject.parseObject(resultInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            StringBuffer userUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            String userInfoUrl = String.format(userUrl.toString(),
                    access_token,
                    openid);
            String userInfoResult = HttpClientUtils.get(userInfoUrl);
            JSONObject userInfoObject = JSONObject.parseObject(userInfoResult);
            String nickname = userInfoObject.getString("nickname");
            UserInfo userInfo = userInfoService.selectUserByOpenid(openid);
            if (userInfo == null){
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            Map<String,String> map = new HashMap<>();
            String phone = userInfo.getPhone();
            if(StringUtils.isEmpty(phone)){
                map.put("openid",userInfo.getOpenid());
            }else{
                map.put("openid","");
            }
            //返回用户名称
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)){
                // 如果用户名称为空，返回用户昵称，
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)){
                // 如果用户昵称为空，返回手机号
                name = userInfo.getPhone();
            }
            map.put("name",name);
            String token = JwtHelper.createToken(userInfo.getId(),name);
            map.put("token",token);

            return "redirect:http://localhost:3000/weixin/callback" +
                    "?token="+map.get("token")
                    + "&openid="+map.get("openid")
                    +"&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //返回微信登录二维码需要参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getWxParam() throws UnsupportedEncodingException {
        String appid = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        String scope = "snsapi_login";

        String redirectUrl = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,"utf-8");

        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("scope",scope);
        map.put("redirectUrl",redirectUrl);
        map.put("state", System.currentTimeMillis());

        return R.ok().data(map);
    }

}
